# coding=utf-8
import os
import re
from datetime import datetime

from openpyxl import Workbook
from openpyxl import load_workbook
# 指定要遍历的目录路径
directory = './pa/0716'
txtpath = []
txtname = []
# 遍历目录中的所有项目
for item in os.listdir(directory):
    # 拼接项目的完整路径
    item_path = os.path.join(directory, item)
    print(item_path)
    txtpath.append(item_path)
    txtname.append(item)

current_date = datetime.now().strftime('%Y-%m-%d')
file_excel = "log_data{}.xlsx".format(current_date)
print(file_excel)
try:
    wb = load_workbook(file_excel)
except FileNotFoundError:
        # 如果文件不存在，则创建新的工作簿
    wb = Workbook()

# 激活工作表
ws = wb.active

for i ,filename in enumerate(txtname):
    print(filename)
    # 检查工作表是否存在，如果不存在则创建一个新的工作表
    if filename not in wb.sheetnames:
        ws = wb.create_sheet(title=filename)
    else:
        ws = wb[filename]

    # 写入数据到工作表
    #ws.append(["time", "height", "temperature", "press"])
    ws.append(["time","press"])
    with open(txtpath[i], 'r', encoding='gbk', errors='ignore') as file:
        print('test')
        # i = 0
        # t1 = -1
        for line in file:
            print(line)
            #line[:9]

            # time_point = '20:48:01'
            #pattern = r"\[(\d{2}:\d{2}:\d{2}.\d{3})\].*?height : (\d+\.\d+)m, temperature : (\d+\.\d+)oC, press : (\d+\.\d+)Pa"
            #pattern = r"\[(\d{2}:\d{2}:\d{2}\.\d{3})\].*?ght : (\d+\.\d+)m, temperature : (\d+\.\d+)oC,press : (\d+\.\d+)Pa"
            #pattern = r"\[.*?(\d{2}:\d{2}:\d{2}\.\d{3})\].*?, temperature : (\d+\.\d+)oC, press : (\d+\.\d+)Pa"
            pattern = r"\[(\d{2}:\d{2}:\d{2}\.\d{3})\].*?,\s*press:\s*(\d+\.\d+)Pa"
            #pattern = r"\[.*?(\d{2}:\d{2}:\d{2}\.\d{3})\].*?PRESS is (\d+\.\d+)"
            #pattern = "\[(\d{2}:\d{2}:\d{2}.\d{3})\].*height : (\d+\.\d+)m, temperature : (\d+\.\d+)oC, press : (\d+\.\d+)Pa"
            # pattern = r"\[(\d{2}:48:01.\d{3})\].*height : (\d+\.\d+)m, temperature : (\d+\.\d+)oC, press : (\d+\.\d+)Pa"
            match = re.search(pattern, line)

            if match:
                time = match.group(1)
                #height = match.group(2)
                #temperature = match.group(3)
                press = match.group(2)
                #temperature = match.group(2)
                #press = match.group(3)

                # t = int(time[:2]) #截取时间 时
                # print(t)

                #ws.append([time, height, temperature, press])
                #ws.append([time,temperature, press])
                ws.append([time, press])

                # if t != t1:
                #     print("enter")
                #     ws.append([time, height, temperature, press])
                #     t1 = t

                print("时间:", time)
                #print("height 值:", height)
                #print("temperature 值:", temperature)
                print("press值:", press)


            else:
                # continue
                print("未匹配到日志信息")
# 保存工作簿
wb.save(file_excel)







